package com.baidu.thirdlib.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.thirdlib.BaseActivity;
import com.baidu.thirdlib.R;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.kvin.toolkit.constants.Interaction;
import com.kvin.toolkit.utils.ToastUtils;
import com.kvin.toolkit.utils.system.KeyboardUtils;
import com.kvin.toolkit.utils.system.PermissionUtils;
import com.sqm.baidumaplib.MapHelper;
import com.sqm.baidumaplib.PoiOverlay;

public class MapActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG_POI = "poi";
    public static final int LOCATED = 1;
    private EditText keyWord;
    private Button search;
    private Button next;
    private Button jump;
    private MapView mMv;
    private BaiduMap mBaiduMap;

    //poi
    private PoiSearch poiSearch;
    private int index;
    private Button location;

    //location
    private LocationClient locClient;
    private boolean isFirstLoc = true;
    private BitmapDescriptor locationMarker;
    public static final String[] lp = new String[]{Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_SETTINGS
    };
    private BDLocation mLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //*初始化百度地图的上下文必须是应用程序的，否则会报错滴
//        MapHelper.initSDK(getApplicationContext());
        setContentView(R.layout.activity_map);
        initView();

    }

    private void initView() {
        this.mMv = (MapView) findViewById(R.id.mapV);
        this.next = (Button) findViewById(R.id.next);
        this.search = (Button) findViewById(R.id.search);
        this.location = (Button) findViewById(R.id.location);
        this.jump = (Button) findViewById(R.id.jump);
        this.keyWord = (EditText) findViewById(R.id.keyWord);
        this.search.setOnClickListener(this);
        this.next.setOnClickListener(this);
        this.location.setOnClickListener(this);
        this.jump.setOnClickListener(this);

        //set map
        //        mMv.removeViewAt(0);//0  map view
//        mMv.removeViewAt(1);//
        mMv.removeViewAt(2);//zoom up or down  view
        mBaiduMap = mMv.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setBuildingsEnabled(true);
        mBaiduMap.setTrafficEnabled(true);
        LatLng lng = new LatLng(30.51667, 114.31667);//wuhan
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLngZoom(lng, 16);
        mBaiduMap.setMapStatus(update);

        locClient = new LocationClient(this);


    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.search) {
            searchPoi();
        } else if (v.getId() == R.id.next) {
            index++;
            searchPoi();
            KeyboardUtils.closeKeyboard(this);

        } else if (v.getId() == R.id.location) {
            backToMyLocation();
        } else if (v.getId() == R.id.jump) {
            skip(LocationDemo.class);
        }
    }

    private void skip(Class<?> objCls) {
        startActivity(new Intent(this, objCls));
    }

    private void backToMyLocation() {
        isFirstLoc=true;
        PermissionUtils.checkGPS(this);
        if (PermissionUtils.isPermitted(this, lp)) {
            launchLocation();
        } else {
            PermissionUtils.requestPermission(this, lp, Interaction.Code.REQUEST_LOCATION);
        }
    }

    /**
     * launch location
     */
    private void launchLocation() {
        //locationMarker = BitmapDescriptorFactory.fromResource(R.mipmap.my_location);
        mBaiduMap.setMyLocationEnabled(true);//
        //set Location mode
//        LocationMode locationMode = LocationMode.NORMAL;
//        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(locationMode, true, null));
        locClient.registerLocationListener(new OnLocationListener());

        locClient.setLocOption(MapHelper.getDefaultOptions());//bind location configs
        locClient.start();//开始定位


    }

    /**
     * poi search
     */
    private void searchPoi() {

        if (isFirstLoc) {
            mMv.setTag(TAG_POI);
            launchLocation();
            return;
        }
        launchSearch();
    }

    /**
     * launch search
     */
    private void launchSearch() {
        poiSearch = PoiSearch.newInstance();
        poiSearch.setOnGetPoiSearchResultListener(mPoiSearchListener);
        //基于城市兴趣点搜索
        PoiCitySearchOption options = new PoiCitySearchOption();
        StringBuffer sb = new StringBuffer(256);

        mLocation = locClient.getLastKnownLocation();

        options.city(mLocation.getCity())
                .pageNum(index)
                .keyword(keyWord.getText().toString());
        poiSearch.searchInCity(options);
    }


    /**
     * poi search result
     */
    private OnGetPoiSearchResultListener mPoiSearchListener = new OnGetPoiSearchResultListener() {
        @Override
        public void onGetPoiResult(PoiResult poiResult) {
            if (poiResult == null || poiResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                Toast.makeText(MapActivity.this, "sorry we cannot find any results", Toast.LENGTH_SHORT).show();
            } else if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                //清理地图上旧的数据
                mBaiduMap.clear();
                PoiOverlay overlay = newPoiOverlay(mBaiduMap);
                //设置点击覆盖物监听事件
                mBaiduMap.setOnMarkerClickListener(overlay);
                //overlay.onPoiClick()
                overlay.setData(poiResult);
                overlay.addToMap();
                overlay.zoomToSpan();//缩放地图至视野范围
                return;
            }
        }

        @Override
        public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
            if (poiDetailResult.error != SearchResult.ERRORNO.NO_ERROR) {
                Toast.makeText(MapActivity.this, "error", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MapActivity.this, poiDetailResult.getName() + ":" + poiDetailResult.getAddress(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

        }
    };


    /**
     * poi overlay factory
     */
    public PoiOverlay newPoiOverlay(BaiduMap baiduMap) {
        return new PoiOverlay(baiduMap) {
            @Override
            public boolean onPoiClick(int index) {
                PoiInfo poi = getPoiResult().getAllPoi().get(index);
                ToastUtils.simpleToast(MapActivity.this, poi.address);
                return true;
            }
        };
    }

    @Override
    protected void onResume() {
        mMv.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMv.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        locClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMv.onDestroy();
        super.onDestroy();
    }


    /**
     * 定位SDK监听函数
     */
    public class OnLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMv == null)
                return;
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }

            if (mMv.getTag() != null && mMv.getTag().toString().equals(TAG_POI)) {
                mHandler.sendEmptyMessage(LOCATED);
            }


        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

        public void onReceivePoi(BDLocation poiLocation) {

        }
    }


    @Override
    public void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case LOCATED:
                launchSearch();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Interaction.Code.REQUEST_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    launchLocation();
                }
                break;
        }
    }
}
